package com.bestcem.xm.user.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.alibaba.fastjson.JSON;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.componet.filestorage.service.StorageService;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.user.config.properties.SettingProperties;
import com.bestcem.xm.user.constant.UserCacheKeyConstant;
import com.bestcem.xm.user.dao.OrganizationDao;
import com.bestcem.xm.user.dao.OrganizationQuotainfoDao;
import com.bestcem.xm.user.entity.pojo.OrganizationDO;
import com.bestcem.xm.user.entity.pojo.OrganizationQuotainfoDO;
import com.bestcem.xm.user.entity.pojo.QuotaInfoQueryDO;
import com.bestcem.xm.user.enums.*;
import com.bestcem.xm.user.grpc.client.BpSurveyQuotaGrpcService;
import com.bestcem.xm.user.grpc.client.OmUserGrpcService;
import com.bestcem.xm.user.grpc.client.PackageGrpcService;
import com.bestcem.xm.user.grpc.client.dto.OmUserDTO;
import com.bestcem.xm.user.grpc.client.dto.PackageDTO;
import com.bestcem.xm.user.grpc.client.dto.RelationDTO;
import com.bestcem.xm.user.mq.message.user.SmsMessage;
import com.bestcem.xm.user.service.*;
import com.bestcem.xm.user.service.dto.PageResponseDTO;
import com.bestcem.xm.user.service.dto.user.*;
import com.bestcem.xm.user.util.business.DataBaseUtil;
import com.bestcem.xm.user.util.convert.OrganizationQuotainfoConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 公司限额统计
 *
 * @author jishuo.yan <jishuo.yan@idiaoyan.com>
 * @date 2022/3/21 14:12
 */
@Slf4j
@Service
public class OrganizationQuotainfoImpl implements OrganizationQuotainfoService {

    @Resource
    private OrganizationQuotainfoDao organizationQuotainfoDao;

    @Resource
    private OrganizationQuotainfoConvert organizationQuotainfoConvert;

    @Resource
    private OrganizationDao organizationDao;

    @Resource
    private RedisService redisService;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private OmUserGrpcService userOmUserGrpcService;

    @Resource
    private PackageGrpcService packageGrpcService;

    @Resource
    private SettingProperties settingProperties;

    @Resource
    private MailService mailService;

    @Resource
    private UserSmtpService userSmtpService;

    @Resource
    private UserSmsService userSmsService;

    //@Resource
    //private UserMessageSender userMessageSender;

    /*@Resource
    private OssService ossService;*/

    @Autowired
    private StorageService storageService;

    @Resource
    private BpSurveyQuotaGrpcService userBpSurveyQuotaGrpcService;

    @Override
    public ServiceResult<String> insertSelective(OrganizationQuotainfoDTO organizationQuotainfoDTO) {
        if (Objects.isNull(organizationQuotainfoDTO)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "公司限额信息为空");
        }
        return ServiceResult.success(organizationQuotainfoDao.insertSelective(organizationQuotainfoConvert.dtoToDo(organizationQuotainfoDTO)));
    }

    @Override
    public ServiceResult<Integer> updateByPrimaryKeySelective(OrganizationQuotainfoDTO organizationQuotainfoDTO) {
        if (Objects.isNull(organizationQuotainfoDTO)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "公司限额信息为空");
        }
        return ServiceResult.success(organizationQuotainfoDao.updateByPrimaryKeySelective(organizationQuotainfoConvert.dtoToDo(organizationQuotainfoDTO)));
    }

    @Override
    public ServiceResult<List<OrganizationQuotainfoDTO>> selectBySelective(OrganizationQuotainfoDTO organizationQuotainfoDTO) {
        if (Objects.isNull(organizationQuotainfoDTO)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "公司限额信息为空");
        }
        List<OrganizationQuotainfoDO> orgQuotainfoDOS = organizationQuotainfoDao.selectBySelective(organizationQuotainfoConvert.dtoToDo(organizationQuotainfoDTO));
        return ServiceResult.success(organizationQuotainfoConvert.dosToDtos(orgQuotainfoDOS));
    }

    @Override
    public ServiceResult<PageResponseDTO<OrganizationQuotainfoDTO>> listPageByQuotaInfo(QuotaInfoQueryDTO quotaInfoQueryDTO) {
        QuotaInfoQueryDO quotaInfoQueryDO = quotaInfoQueryDTO2DO(quotaInfoQueryDTO);
        if (StringUtils.isNotEmpty(quotaInfoQueryDTO.getOrgId())
                && !ObjectId.isValid(quotaInfoQueryDTO.getOrgId())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "公司id格式不对");
        }
        if (StringUtils.isBlank(quotaInfoQueryDO.getPlatform())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "合作商code不能为空");
        }
        if (Objects.nonNull(quotaInfoQueryDO.getRespondentLte()) && quotaInfoQueryDO.getRespondentLte() < 0) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "累计答卷不能小于0");
        }
        if (Objects.nonNull(quotaInfoQueryDO.getProjectLte()) && quotaInfoQueryDO.getProjectLte() < 0) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "累计问卷不能小于0");
        }

        // 获取查询参数
        if (StringUtils.isNotEmpty(quotaInfoQueryDO.getOrgId())) {
            OrganizationDO organizationDO = new OrganizationDO();
            organizationDO.setOrgId(quotaInfoQueryDO.getOrgId());
            organizationDO.setSourceRemark(quotaInfoQueryDO.getPlatform());
            List<OrganizationDO> organizations = organizationDao.selectBySelective(organizationDO);
            if (CollectionUtils.isEmpty(organizations)) {
                return ServiceResult.fail(ResourceErrorCodeEnum.NO_DATA, "公司不存在");
            }
            OrganizationQuotainfoDO organizationQuotainfoDO = organizationQuotainfoDao.getByOrgId(organizationDO.getOrgId());
            if (Objects.isNull(organizationQuotainfoDO)) {
                return ServiceResult.fail(ResourceErrorCodeEnum.NO_DATA, "公司限额信息不存在");
            }
            List<OrganizationQuotainfoDTO> list = Collections.singletonList(organizationQuotainfoConvert.doToDto(organizationQuotainfoDO));
            return ServiceResult.success(new PageResponseDTO<>(list, 1L, 1));
        }

        quotaInfoQueryDO.setPlatform(quotaInfoQueryDO.getPlatform());
        // 统计数量
        long count = organizationQuotainfoDao.countQuataInfo(quotaInfoQueryDO);
        PageResponseDTO<OrganizationQuotainfoDTO> pageDto = new PageResponseDTO<>();
        if (count == 0) {
            pageDto.setTotal(0L);
            return ServiceResult.success(pageDto);
        }
        // 分页查询列表
        Integer skip = (quotaInfoQueryDO.getPage() - 1) * quotaInfoQueryDO.getPerPage();
        quotaInfoQueryDO.setSkip(skip);
        List<OrganizationQuotainfoDO> orgQuotaInfos = organizationQuotainfoDao.listQuataInfo(quotaInfoQueryDO);
        List<OrganizationQuotainfoDTO> orgQuotainfoDTOS = organizationQuotainfoConvert.dosToDtos(orgQuotaInfos);
        pageDto = new PageResponseDTO<>(orgQuotainfoDTOS, count, quotaInfoQueryDO.getPage());

        return ServiceResult.success(pageDto);
    }

    @Override
    public ServiceResult<PageResponseDTO<OrganizationQuotainfoDTO>> listPageByOrgId(String orgId, Integer page, Integer size) {
        // 参数校验
        if (null == page || page < 1) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "currentPage不能小于1");
        }
        if (null == size || size < 1) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "pageSize不能小于1");
        }

        // 统计数量
        long count = organizationQuotainfoDao.countByOrgId(orgId);
        PageResponseDTO<OrganizationQuotainfoDTO> pageDto = new PageResponseDTO<>();
        if (count == 0) {
            pageDto.setTotal(0L);
            return ServiceResult.success(pageDto);
        }

        // 分页查询列表
        List<OrganizationQuotainfoDO> orgQuotaInfos = organizationQuotainfoDao.listPageByOrgId(orgId, page, size);
        List<OrganizationQuotainfoDTO> orgQuotainfoDTOS = organizationQuotainfoConvert.dosToDtos(orgQuotaInfos);
        pageDto = new PageResponseDTO<>(orgQuotainfoDTOS, count, page);
        return ServiceResult.success(pageDto);
    }

    @Override
    public ServiceResult<OrganizationQuotainfoDTO> getByOrgId(String orgId) {
        String consumption = UserCacheKeyConstant.USER_PACK_CONSUMPTION + orgId;
        Map<Object, Object> map = redisService.hashGetAll(consumption);
        OrganizationQuotainfoDTO orgDTO = new OrganizationQuotainfoDTO();
        if (map.isEmpty()) {
            OrganizationQuotainfoDO quotaInfo = organizationQuotainfoDao.getByOrgId(orgId);
            if (Objects.isNull(quotaInfo)) {
                // 新增一条数据
                quotaInfo = new OrganizationQuotainfoDO();
                quotaInfo.setOrgId(orgId);
                organizationQuotainfoDao.insertSelective(quotaInfo);
            }
            orgDTO.setUserTotal(Optional.ofNullable(quotaInfo.getUserTotal()).orElse(0));
            orgDTO.setRespondentTotal(Optional.ofNullable(quotaInfo.getRespondentTotal()).orElse(0).longValue());
            orgDTO.setProjectTotal(Optional.ofNullable(quotaInfo.getProjectTotal()).orElse(0));
            orgDTO.setMemberIndTotal(Optional.ofNullable(quotaInfo.getMemberIndTotal()).orElse(0));
            orgDTO.setDatasourceTotal(Optional.ofNullable(quotaInfo.getDatasourceTotal()).orElse(0));

            redisService.hashIncr(consumption, QuotaConsumptionEnum.USER.getKey(), Long.valueOf(Optional.ofNullable(quotaInfo.getUserTotal()).orElse(0)));
            redisService.hashIncr(consumption, QuotaConsumptionEnum.RESPONDENT.getKey(), Long.valueOf(Optional.ofNullable(quotaInfo.getRespondentTotal()).orElse(0)));
            redisService.hashIncr(consumption, QuotaConsumptionEnum.PROJECT.getKey(), Long.valueOf(Optional.ofNullable(quotaInfo.getProjectTotal()).orElse(0)));
            redisService.hashIncr(consumption, QuotaConsumptionEnum.MEMBER_IND.getKey(), Long.valueOf(Optional.ofNullable(quotaInfo.getMemberIndTotal()).orElse(0)));
            redisService.hashIncr(consumption, QuotaConsumptionEnum.DATASOURCE.getKey(), Long.valueOf(Optional.ofNullable(quotaInfo.getDatasourceTotal()).orElse(0)));
        } else {
            orgDTO.setUserTotal(Integer.parseInt(map.getOrDefault(QuotaConsumptionEnum.USER.getKey(), 0).toString()));
            orgDTO.setRespondentTotal(Long.parseLong(map.getOrDefault(QuotaConsumptionEnum.RESPONDENT.getKey(), 0).toString()));
            orgDTO.setProjectTotal(Integer.parseInt(map.getOrDefault(QuotaConsumptionEnum.PROJECT.getKey(), 0).toString()));
            orgDTO.setMemberIndTotal(Integer.parseInt(map.getOrDefault(QuotaConsumptionEnum.MEMBER_IND.getKey(), 0).toString()));
            orgDTO.setDatasourceTotal(Integer.parseInt(map.getOrDefault(QuotaConsumptionEnum.DATASOURCE.getKey(), 0).toString()));
        }
        // 问卷和答卷数，改为查询python数据
        OrganizationQuotainfoDTO surveyQuotaDTO = userBpSurveyQuotaGrpcService.getQuotaByOrgId(orgId);
        orgDTO.setProjectTotal(surveyQuotaDTO.getProjectTotal());
        orgDTO.setRespondentTotal(surveyQuotaDTO.getRespondentTotal());
        return ServiceResult.success(orgDTO);
    }

    @Override
    public ServiceResult<Void> updateQuotaConsumption(QuotaConsumptionDTO quotaConsumptionDTO) {
        if (Objects.isNull(quotaConsumptionDTO)) {
            log.error("[USER] 参数为空，跳过消息");
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "参数为空");
        }
        String orgId = quotaConsumptionDTO.getOrgId();
        Integer amount = quotaConsumptionDTO.getAmount();
        String type = quotaConsumptionDTO.getType();
        QuotaConsumptionEnum quotaType = QuotaConsumptionEnum.getByType(type);
        if (Objects.isNull(quotaType)) {
            log.error("[USER] 限额更新类型错误，跳过消息");
            return ServiceResult.fail("限额更新类型错误");
        }
        OrganizationQuotainfoDO quotaInfo = organizationQuotainfoDao.getByOrgId(orgId);
        if (Objects.isNull(quotaInfo)) {
            // 新增一条数据
            quotaInfo = new OrganizationQuotainfoDO();
            quotaInfo.setOrgId(orgId);
            organizationQuotainfoDao.insertSelective(quotaInfo);
        }

        OrganizationQuotainfoDO orgQuotainfoDO = new OrganizationQuotainfoDO();
        orgQuotainfoDO.setOrgId(orgId);
        switch (quotaType) {
            case USER:
                orgQuotainfoDO.setUserTotal(amount);
                break;
            case RESPONDENT:
                orgQuotainfoDO.setRespondentTotal(amount);
                break;
            case PROJECT:
                orgQuotainfoDO.setProjectTotal(amount);
                break;
            case MEMBER_IND:
                orgQuotainfoDO.setMemberIndTotal(amount);
                break;
            case DATASOURCE:
                orgQuotainfoDO.setDatasourceTotal(amount);
                break;
            default:
                log.error("[USER] 公司限额类型不存在，跳过消息");
                return ServiceResult.fail("公司限额类型不存在");
        }
        // 除用户限额外，更新限额缓存 （用户限额已更新com.bestcem.xm.user.service.impl.UserServiceImpl.updateUserConsumption)
        if (QuotaConsumptionEnum.USER != quotaType) {
            String consumption = UserCacheKeyConstant.USER_PACK_CONSUMPTION + orgId;
            redisService.hashIncr(consumption, quotaType.getKey(), Long.valueOf(amount));
        }
        Integer result = organizationQuotainfoDao.updateQuotaConsumption(orgQuotainfoDO);
        if (result.equals(0)) {
            return ServiceResult.fail("公司限额数更新失败");
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Boolean> notifyQuotaReachedToUser(QuotaReachedDTO dto) {
        /**
         * 限额通知租户 apps_mysql.user.mq_handlers.notify_quota_reached_to_user
         */
        // 校验参数和event类型
        if (Objects.isNull(dto) || StringUtils.isEmpty(dto.getEvent())) {
            log.error("限额通知租户消息内容不能为空");
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "限额通知租户消息内容不能为空");
        }
        // 获取对应的时间类型枚举
        NotifyQuotaReachedEventEnum eventEnum = NotifyQuotaReachedEventEnum.getByType(dto.getEvent());
        if (Objects.isNull(eventEnum)) {
            log.error("限额通知租户消息event不正确：data error data.event：{}", dto.getEvent());
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "限额通知租户消息event不正确");
        }

        // 通知标题
        String notifyTitle = eventEnum.getNotifyTitle();
        // 邮件模板
        String emailTemplateFileName = eventEnum.getEmailFileTemplateName();

        // 确定收件人
        ServiceResult<UserDTO> userByOrgId = userBusinessService.getAdminUserByOrgId(dto.getOrgId());
        if (!userByOrgId.isSuccess() || Objects.isNull(userByOrgId.getData())) {
            return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, "未查询到管理员用户信息");
        }
        UserDTO user = userByOrgId.getData();
        RelationDTO orgRelatedOp = userOmUserGrpcService.getOrgRelatedOp(dto.getOrgId());
        OmUserDTO omUser = userOmUserGrpcService.getOmUser(orgRelatedOp.getId());
        List<String> mailTo = new ArrayList<>();
        if (StringUtils.isNotBlank(omUser.getEmail())) {
            mailTo.add(omUser.getEmail());
        }
        if (StringUtils.isNotBlank(user.getEmail())) {
            mailTo.add(user.getEmail());
        }
        List<String> smsTo = new ArrayList<>();
        if (StringUtils.isNotBlank(omUser.getPhone())) {
            smsTo.add(omUser.getPhone());
        }
        if (StringUtils.isNotBlank(user.getPhone())) {
            smsTo.add(user.getPhone());
        }

        // 查询租户信息
        ServiceResult<OrganizationDTO> organizationDTOServiceResult = organizationService.selectByPrimaryKey(dto.getOrgId());
        if (!organizationDTOServiceResult.isSuccess() || Objects.isNull(organizationDTOServiceResult.getData())) {
            return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, "未查询到租户信息");
        }
        OrganizationDTO organizationDTO = organizationDTOServiceResult.getData();
        // 查询租户套餐信息
        PackageDTO packageDTO = packageGrpcService.getById(organizationDTO.getPackageId());
        if (Objects.isNull(packageDTO)) {
            return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, "未查询到租户套餐信息：packageId:" + organizationDTO.getPackageId());
        }
        String packName = packageDTO.getName();
        Integer totalQuota = dto.getTotalQuota();

        NotifyQuotaReachedEnum notifyEnum = NotifyQuotaReachedEnum.getByQuotaRate(dto.getQuotaRate());
        // 邮件模板主题
        String mailSubject = notifyEnum.getMailSubject();
        // 获取使用率提示
        String rateStr = notifyEnum.getRateStr();
        if (notifyEnum == NotifyQuotaReachedEnum.CONSUMPTION) {
            int rate = 80;
            if (StringUtils.isNotEmpty(dto.getQuotaRate())) {
                try {
                    rate = new BigDecimal(dto.getQuotaRate()).multiply(BigDecimal.valueOf(100)).intValue();
                } catch (Exception e) {
                    log.error("[USER] 答卷比率转换出错 dto:{}", JSON.toJSONString(dto), e);
                }
            }
            rateStr += rate + "%";
        }
        notifyTitle += notifyEnum.getNotifyTitle();

        // answerQuotaMap的模板参数
        Map<String, Object> answerQuotaMap = new HashMap<>();
        answerQuotaMap.put("pack_name", packName);
        answerQuotaMap.put("total_quota", totalQuota);
        answerQuotaMap.put("rate_str", rateStr);
        String answerQuotaTip = eventEnum.getAnswerQuotaTipResult(answerQuotaMap);
        // 邮件内容的模板参数
        HashMap<String, Object> mailMap = new HashMap<>();
        mailMap.put("answerQuotaTip", answerQuotaTip);
        mailMap.put("name", user.getName());
        mailMap.put("telephone", settingProperties.getBestHotline());
        mailMap.put("url", settingProperties.getSassServerUrl() + "/version");
        mailMap.put("time", DateUtil.convertDteToString(DataBaseUtil.getDate(), "yyyy年MM月dd日"));
        //mailMap.put("email_oss_path", ossService.getUrlPrefix() + "email/");
        mailMap.put("email_oss_path", storageService.getPropertiesValueBy(null, "domain") + storageService.getPropertiesValueBy(null, "base-path") + "email/");
        mailMap.put("org_code", organizationDTO.getCode());
        mailMap.put("org_name", organizationDTO.getName());
        mailMap.put("user_name", user.getUserName());
        mailMap.put("org_id", dto.getOrgId());
        mailMap.put("notify_title", notifyTitle);

        // 查询收件人列表
        UserSmtpDTO smtpParam = new UserSmtpDTO();
        smtpParam.setOrgId(dto.getOrgId());
        smtpParam.setNoticeFlag(BooleanStatusEnum.YES.getStatus());
        ServiceResult<List<UserSmtpDTO>> userSmtpsResult = userSmtpService.selectBySelective(smtpParam);
        if (!userSmtpsResult.isSuccess() || CollectionUtils.isEmpty(userSmtpsResult.getData())) {
            return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, "未查询到该租户公司的收件人邮箱配置信息");
        }
        UserSmtpDTO smtpInfo = userSmtpsResult.getData().get(0);
        // 发送邮件 需要用smtp配置的去发
        JavaMailSenderImpl javaMailSender = mailService.buildMailSender(smtpInfo.getHost(), smtpInfo.getPort(),
                smtpInfo.getAccount(), smtpInfo.getPassword());
        if (CollectionUtils.isNotEmpty(mailTo)) {
            mailService.emailSendAndNotifyOm(javaMailSender, smtpInfo.getSenderName(), mailTo.toArray(new String[mailTo.size()]),
                    null, mailSubject, emailTemplateFileName, mailMap);
        }
        if (CollectionUtils.isNotEmpty(smsTo)) {
            // 发送短信
            // 短信内容的模板参数
            HashMap<String, Object> smsMap = new HashMap<>();
            smsMap.put("name", user.getName());
            smsMap.put("pack_name", packName);
            smsMap.put("total_quota", totalQuota);
            smsMap.put("rate_str", rateStr);
            smsMap.put("best_hotline", settingProperties.getBestHotline());
            smsMap.put("org_code", organizationDTO.getCode());
            smsMap.put("org_name", organizationDTO.getName());
            smsMap.put("user_name", user.getUserName());
            String smsContent = eventEnum.getSmsTemplateResult(smsMap);
            int notifyStatus = NotifyStatusEnum.SEND_FAILED.getType();
            for (String phone : smsTo) {
                try {
                    userSmsService.sendSms(phone, smsContent);
                    notifyStatus = NotifyStatusEnum.IS_SEND.getType();
                } catch (Exception e) {
                    notifyStatus = NotifyStatusEnum.SEND_FAILED.getType();
                }
            }

            // mq通知系统商后台
            SmsMessage smsMessage = new SmsMessage();
            smsMessage.setContent(smsContent)
                    .setName(notifyTitle)
                    .setOrgId(dto.getOrgId())
                    .setReceiver(String.join(",", smsTo))
                    .setSender("")
                    .setType(NotifyTypeEnum.MOBILE.getType())
                    .setStatus(notifyStatus)
                    .setSendTime(DateUtil.convertDteToString(DataBaseUtil.getDate(), DateUtil.NORM_DATETIME_PATTERN))
                    .setParams(JSON.toJSONString(smsMap))
                    .setSmsChannel(NotifySmsChannelEnum.YIMEI.getType());
            // 发送MQ
            //if (StringUtils.isNotBlank(settingProperties.getAppName())) {
            //    userMessageSender.publishOmSmsSyc(smsMessage);
            //}
        }
        return null;
    }

    private QuotaInfoQueryDO quotaInfoQueryDTO2DO(QuotaInfoQueryDTO dto) {
        QuotaInfoQueryDO quotaInfoQueryDO = new QuotaInfoQueryDO();
        if (StringUtils.isNotBlank(dto.getOrgId())) {
            quotaInfoQueryDO.setOrgId(dto.getOrgId());
        }
        if (StringUtils.isNotBlank(dto.getPlatform())) {
            quotaInfoQueryDO.setPlatform(dto.getPlatform());
        }
        if (Objects.nonNull(dto.getPage())) {
            quotaInfoQueryDO.setPage(dto.getPage());
        }
        if (Objects.nonNull(dto.getPerPage())) {
            quotaInfoQueryDO.setPerPage(dto.getPerPage());
        }
        if (Objects.nonNull(dto.getProjectGt())) {
            quotaInfoQueryDO.setProjectGt(dto.getProjectGt());
        }
        if (Objects.nonNull(dto.getProjectLte())) {
            quotaInfoQueryDO.setProjectLte(dto.getProjectLte());
        }
        if (Objects.nonNull(dto.getRespondentGt())) {
            quotaInfoQueryDO.setRespondentGt(dto.getRespondentGt());
        }
        if (Objects.nonNull(dto.getRespondentLte())) {
            quotaInfoQueryDO.setRespondentLte(dto.getRespondentLte());
        }
        return quotaInfoQueryDO;
    }
}
